package cn.oldfeel.spark.base;

import java.util.ArrayList;

import android.app.ActionBar;
import android.app.ActionBar.TabListener;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import cn.oldfeel.spark.R;
import cn.oldfeel.spark.util.DialogUtil;

/**
 * 根布局是垂直布局linearlayout的baseactivity.
 * 
 * @author oldfeel
 * 
 */
public abstract class BaseActivity extends ActionBarActivity {
	private ArrayList<Fragment> list = new ArrayList<Fragment>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppManager.getInstance().addActivity(this);
		getActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * 获取一个intent
	 * 
	 * @param className
	 * @return
	 */
	protected Intent getIntent(Class<?> className) {
		return new Intent(this, className);
	}

	/**
	 * 打开指定activity
	 * 
	 * @param className
	 */
	protected void openActivity(Class<?> className) {
		startActivity(getIntent(className));
	}

	/**
	 * 显示一个可以覆盖上一个toast的toast
	 * 
	 * @param text
	 */
	protected void showToast(String text) {
		DialogUtil.getInstance().showToast(this, text);
	}

	/**
	 * 显示指定fragment
	 * 
	 * @param id
	 * @param fragment
	 */
	protected void showFragment(Fragment fragment) {
		FragmentTransaction trans = getFragmentManager().beginTransaction();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).isAdded()) {
				trans.hide(list.get(i));
			}
		}
		if (fragment.isAdded()) {
			trans.show(fragment);
		} else {
			trans.add(R.id.content_frame, fragment);
			list.add(fragment);
		}
		trans.commit();
	}

	@Override
	protected void onDestroy() {
		AppManager.getInstance().finishActivity(this);
		super.onDestroy();
	}

	/**
	 * 添加tab
	 * 
	 * @param tabListener
	 * @param tabs
	 */
	public void addTab(TabListener tabListener, String... tabs) {
		ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		for (int i = 0; i < tabs.length; i++) {
			actionBar.addTab(actionBar.newTab().setText(tabs[i])
					.setTabListener(tabListener));
		}
	}
}
